//
//  PlanPeopleHeadView.m
//  WanCaiC8
//
//  Created by tangang on 2018/3/31.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "PlanPeopleHeadView.h"
#import "LabCell.h"
#import "MyVM.h"
#import "OtherInfoVC.h"
#import "LotteryNumCell.h"
#import "InformationVM.h"
#import "AdvertisingView.h"

@interface PlanPeopleHeadView()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic ,strong) UICollectionView  *numCollectionView;
@property (nonatomic ,strong) NSArray           *dataArr;




@end

@implementation PlanPeopleHeadView{
    UIImageView *headImage;
    QXLable     *labName;
    QXLable     *labFans;
    UIButton    *btnFocus;
    //    UIButton    *btnExceptional;
    QXLable     *labOpenNum;
    QXLable     *labTime;
    dispatch_source_t _timer;
    NSInteger   selected;
    QXLable     *labPredictedResults;
    QXLable     *labAd1;
    QXLable     *labAd2;
    QXLable     *labAd3;
    
    //记录当前获取的model
    Home_LotteryModel *recordModel;
}

- (instancetype)init{
    if (self=[super init]) {
    
        
        self.backgroundColor=[UIColor whiteColor];
        headImage =[[UIImageView alloc]init];
        headImage.layer.masksToBounds=YES;
        headImage.layer.cornerRadius=25;
        headImage.userInteractionEnabled=YES;
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onclickUserInfo)];
        [headImage addGestureRecognizer:tap];
        [self addSubview:headImage];
        [headImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.equalTo(self).with.offset(defaultLeftMargin);
            make.size.mas_equalTo(CGSizeMake(real_size(50), real_size(50)));
        }];
        
        labName =[[QXLable alloc] initTitle];
        [self addSubview:labName];
        [labName mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(headImage).with.offset(real_size(3));
            make.left.equalTo(headImage.mas_right).with.offset(defaultLeftMargin);
        }];
        
        labFans =[[QXLable alloc]init];
        [self addSubview:labFans];
        [labFans mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(labName);
            make.bottom.equalTo(headImage.mas_bottom).with.offset(-3);
        }];
        
        btnFocus =[[UIButton alloc]init];
        [btnFocus setTitle:@"关注" forState:UIControlStateNormal];
        btnFocus.layer.masksToBounds=YES;
        btnFocus.layer.borderWidth=1.0;
        [btnFocus addTarget:self action:@selector(onclickFocus:) forControlEvents:UIControlEventTouchUpInside];
        btnFocus.layer.cornerRadius=2.0;
        [btnFocus.titleLabel setFont:[UIFont systemFontOfSize:10]];
        btnFocus.layer.borderColor=NAVCOLOR.CGColor;
        [btnFocus setTitleColor:NAVCOLOR forState:UIControlStateNormal];
        [self addSubview:btnFocus];
        [btnFocus mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(labFans);
            make.left.equalTo(labFans.mas_right).with.offset(defaultLeftMargin);
            make.size.mas_equalTo(CGSizeMake(real_size(35), real_size(20)));
        }];
        
        UIView *line=[[UIView alloc]init];
        line.backgroundColor=DEFAULTBGCOLOR;
        [self addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(headImage.mas_bottom).with.offset(real_size(10));
            make.left.right.equalTo(self);
            make.height.mas_equalTo(@.7);
        }];
        
        labOpenNum=[[QXLable alloc]init];
        [self addSubview:labOpenNum];
        [labOpenNum mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headImage);
            make.top.equalTo(line).with.offset(defaultLeftMargin);
        }];
        
        [self addSubview:self.numCollectionView];
        [self.numCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headImage);
            make.bottom.equalTo(labOpenNum);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-30, real_size(25)));
        }];
        
        labTime=[[QXLable alloc]init];
        labTime.textAlignment=NSTextAlignmentRight;
        [self addSubview:labTime];
//        [labTime sizeToFit];
        [labTime mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self).with.offset(-defaultLeftMargin);
            make.centerY.equalTo(labOpenNum);
        }];
        
        UIView *line1=[[UIView alloc]init];
        line1.backgroundColor=DEFAULTBGCOLOR;
        [self addSubview:line1];
        [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.bottom.equalTo(self);
            make.height.mas_equalTo(@.7);
        }];
        
        // MARK:
        /*-----------*/
    
    }
    return self;
}


#pragma mark -- 关注
- (void)onclickFocus:(UIButton *)sender{
    
    WS(weakSelf);
    if (self.userInfo.isFollow) {
        UIAlertController *alertCtrl=[UIAlertController alertControllerWithTitle:nil message:@"确定不在关注此人" preferredStyle:UIAlertControllerStyleAlert];
        [alertCtrl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        UIAlertAction *sure=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            sender.userInteractionEnabled=NO;
            [[MyVM manage] cancleFollowWithId:self.userId Success:^(id returnValue) {
                weakSelf.userInfo.isFollow=NO;
                [sender setTitle:@"关注" forState:UIControlStateNormal];
                sender.layer.borderColor=NAVCOLOR.CGColor;
                [sender setTitleColor:NAVCOLOR forState:UIControlStateNormal];
                sender.userInteractionEnabled=YES;
                weakSelf.userInfo.Fans=[NSString stringWithFormat:@"%ld",[weakSelf.userInfo.Fans integerValue]-1];
                [weakSelf updateUI];
            } andFail:^(NSString *errorMessage, NSError *error) {
                sender.userInteractionEnabled=YES;
            }];
        }];
        [alertCtrl addAction:sure];
        [[TGTools viewController:self] presentViewController:alertCtrl animated:YES completion:nil];
        
        
    }else{
        [[MyVM manage] addFollowWithId:self.userId Success:^(id returnValue) {
            weakSelf.userInfo.isFollow=YES;
            [sender setTitle:@"已关注" forState:UIControlStateNormal];
            sender.layer.borderColor=DEFAULTTEXTGRAYCOLOR.CGColor;
            [sender setTitleColor:DEFAULTTEXTGRAYCOLOR forState:UIControlStateNormal];
            sender.userInteractionEnabled=YES;
            weakSelf.userInfo.Fans=[NSString stringWithFormat:@"%ld",[weakSelf.userInfo.Fans integerValue]+1];
            [weakSelf updateUI];
        } andFail:^(NSString *errorMessage, NSError *error) {
            sender.userInteractionEnabled=YES;
        }];
    }
}

- (void)onclickUserInfo{
    if ([UserModel userModel].UserId.length>0) {
        OtherInfoVC *vc=[[OtherInfoVC alloc]init];
        vc.userId=self.userId;
        [[TGTools viewController:self].navigationController pushViewController:vc animated:YES];
    }else{
        [[BaseVM manage] login];
    }
    
}


- (void)onclickExceptional{
    if (self.clickExceptional) {
        self.clickExceptional();
    }
}


- (void)setUserId:(NSString *)userId{
    _userId=userId;
    WS(weakSelf);
    [[MyVM manage] getUserInfoWithUserId:userId WithSuccess:^(id returnValue) {
        weakSelf.userInfo=returnValue;
        [weakSelf updateUI];
        if ([UserModel userModel].UserId.length>0) {
            [weakSelf hasFollow];
        }
        
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

-(void)loadData{
    
    WS(weakSelf);
    
    [[HomePageVM manage] getLotteryInfoWithId:_lType Success:^(id returnValue) {
        weakSelf.lotteryModel=returnValue;
        
        
        //返回给PlanPeopleVC
        weakSelf.returnDataBlock(weakSelf.lotteryModel.CurrentIssue);
        
        NSMutableAttributedString *attStr=[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@期\n%@",weakSelf.lotteryModel.Issue,[weakSelf.lotteryModel.OpenNum stringByReplacingOccurrencesOfString:@"," withString:@" "]]];
        [attStr addAttribute:NSForegroundColorAttributeName value:NAVCOLOR range:NSMakeRange(weakSelf.lotteryModel.Issue.length+1, attStr.length-weakSelf.lotteryModel.Issue.length-1)];
        [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(weakSelf.lotteryModel.Issue.length+1, attStr.length-weakSelf.lotteryModel.Issue.length-1)];
        NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
        paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
        paraStyle.lineSpacing = 5; //设置行间距
        
        [attStr addAttribute:NSParagraphStyleAttributeName value:paraStyle range:NSMakeRange(0, attStr.length)];
        if ([[BaseVM manage] getType:[weakSelf.lType integerValue]]==LotteryNumTypeBrings) {
            
            
            [attStr addAttribute:NSForegroundColorAttributeName value:DEFAULTTEXTBLUECOLOR range:NSMakeRange(attStr.length-5, 5)];
        }else if ([[BaseVM manage] getType:[weakSelf.lType integerValue]]==LotteryNumTypeChromosphere||[[BaseVM manage] getType:[weakSelf.lType integerValue]]==LotteryNumTypeSevenLecai){
            [attStr addAttribute:NSForegroundColorAttributeName value:DEFAULTTEXTBLUECOLOR range:NSMakeRange(attStr.length-3, 3)];
        }else if ([[BaseVM manage] getType:[weakSelf.lType integerValue]]==LotteryNumTypeLottery){
            self.numCollectionView.hidden=NO;
            [self.numCollectionView reloadData];
            attStr=[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@期\n\n",weakSelf.lotteryModel.Issue]];
        }
        
        labOpenNum.attributedText=attStr;
        [self performSelector:@selector(updateData) withObject:nil afterDelay:15];
        
        [weakSelf startTimer];
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
    
}


#pragma mark -- 查询用户是否关注
- (void)hasFollow{
    WS(weakSelf);
    [[MyVM manage] getHasFollowWithId:self.userId andSuccess:^(id returnValue) {
        weakSelf.userInfo.isFollow=[[returnValue objectForKey:@"Followed"] boolValue];
        if (weakSelf.userInfo.isFollow) {
            btnFocus.layer.borderColor=DEFAULTTEXTGRAYCOLOR.CGColor;
            [btnFocus setTitleColor:DEFAULTTEXTGRAYCOLOR forState:UIControlStateNormal];
            [btnFocus setTitle:@"已关注" forState:UIControlStateNormal];
        }else{
            btnFocus.layer.borderColor=NAVCOLOR.CGColor;
            [btnFocus setTitleColor:NAVCOLOR forState:UIControlStateNormal];
            
        }
        
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

- (void)setLType:(NSString *)lType{
    _lType=lType;
    
    [self loadData];
}

#pragma mark -- 启动定时器
- (void)startTimer{
    
    [self cancleTimer];
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        
    
        if (![self.lotteryModel.OpenTime isEqualToString:@"正在开奖"]) {
            NSArray *timeArr=[self.lotteryModel.OpenTime componentsSeparatedByString:@":"];
            int hour=[timeArr[0] intValue];
            int minutes=[timeArr[1] intValue];
            int second=[timeArr[2] intValue];
            if (second>0) {
                second-=1;
                self.lotteryModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
            }else if (minutes>0){
                minutes-=1;
                second=59;
                self.lotteryModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
            }else if (hour>0){
                hour-=1;
                minutes=59;
                second=59;
                self.lotteryModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
            }else{
                [self cancleTimer];
                self.lotteryModel.OpenTime=@"正在开奖";
            }
        
            
            
        }else{
            
            [self cancleTimer];
            
            recordModel = self.lotteryModel;
        }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSMutableAttributedString *attStr=[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"距%@期截止\n%@",self.lotteryModel.CurrentIssue,self.lotteryModel.OpenTime]];
            [attStr addAttribute:NSForegroundColorAttributeName value:NAVCOLOR range:NSMakeRange(attStr.length-self.lotteryModel.OpenTime.length, self.lotteryModel.OpenTime.length)];
            [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(attStr.length-self.lotteryModel.OpenTime.length, self.lotteryModel.OpenTime.length)];
            NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
            paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
            paraStyle.lineSpacing = 5; //设置行间距
            paraStyle.alignment=NSTextAlignmentRight;
            [attStr addAttribute:NSParagraphStyleAttributeName value:paraStyle range:NSMakeRange(0, attStr.length)];
            labTime.attributedText=attStr;
           
        });
        
    });
    dispatch_resume(_timer);
}

- (void)updateData{
    self.lType=self.lType;
}

- (void)cancleTimer{
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

- (void)updateUI{
    labName.text=self.userInfo.NickName;
    labFans.text=[NSString stringWithFormat:@"粉丝：%@",self.userInfo.Fans];
    [headImage sd_setImageWithURL:[NSURL URLWithString:self.userInfo.Avater] placeholderImage:[UIImage imageNamed:@"avatar"]];
}


#pragma mark - collectionView代理函数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
        return self.lotteryModel.LotteryArr.count;
  
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
        LotteryNumCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"LotteryNumCell" forIndexPath:indexPath];
        NSString *title=self.lotteryModel.LotteryArr[indexPath.row];
        [cell setTitle:title andType:LotteryNumTypeLottery];
        if ([title isEqualToString:@"+"]) {
            [cell setTitleColor:NAVCOLOR];
        }
        return cell;
  
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(0, 0, 0, 10);
}



-(void)dealloc{
    
    NSLog(@"planpeopleHeadView销毁");
}
#pragma mark -- 懒加载


- (UICollectionView *)numCollectionView{
    if (_numCollectionView==nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setItemSize:CGSizeMake(real_size(25), real_size(25))];
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        layout.minimumInteritemSpacing = 0.0;
        layout.minimumLineSpacing = 0.0;
        _numCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _numCollectionView.delegate = self;
        _numCollectionView.dataSource = self;
        _numCollectionView.hidden=YES;
        _numCollectionView.backgroundColor=[UIColor clearColor];
        _numCollectionView.showsVerticalScrollIndicator=NO;
        [_numCollectionView registerClass:[LotteryNumCell class] forCellWithReuseIdentifier:@"LotteryNumCell"];
    }
    return _numCollectionView;
}

- (NSArray *)dataArr{
    if (!_dataArr) {
        _dataArr=@[@"10期",@"20期",@"30期",@"50期",@"100期"];
    }
    return _dataArr;
}

@end
